﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace Tisn
{
    public class TisnUtils
    {
        public static string FileSha1(string FileName)
        {
            SHA1 sha1 = SHA1.Create();
            var bs = File.ReadAllBytes(FileName);
            return sha1.ComputeHash(bs).ToHex();
        }
    }

    public static class TisnHelper
    {
        public static int Revert(this int self)
        {
            var tmp = BitConverter.GetBytes(self);
            tmp = tmp.Reverse().ToArray();
            return BitConverter.ToInt32(tmp, 0);
        }
        public static uint Revert(this uint self)
        {
            var tmp = BitConverter.GetBytes(self);
            tmp = tmp.Reverse().ToArray();
            return BitConverter.ToUInt32(tmp, 0);
        }

        public static int ToInt32(this byte[] self, int index = 0)
        {
            return BitConverter.ToInt32(self, index);
        }
        public static uint ToUInt32(this byte[] self, int index = 0)
        {
            return BitConverter.ToUInt32(self, index);
        }

        public static byte[] ToBytes(this string self, Encoding encoding = null)
        {
            if (encoding == null)
                encoding = Encoding.ASCII;
            return encoding.GetBytes(self);
        }

        public static byte[] HexToBytes(this string self)
        {
            var str = (string)self.Clone();
            str = str.Replace(" ", "");
            if (str.Length % 2 != 0)
                return null;
            byte[] result = new byte[str.Length / 2];
            for (var i = 0; i < str.Length; i += 2)
            {

                result[i / 2] = byte.Parse(str.Substring(i, 2), System.Globalization.NumberStyles.HexNumber);
            }
            return result;
        }

        public static string ToHex(this byte[] self)
        {
            var result = "";
            for(var i = 0; i < self.Length; i++)
            {
                result += string.Format("{0:X2}", self[i]);
            }
            return result;
        }

        public static string ToBase64(this byte[] self)
        {
            return Convert.ToBase64String(self);
        }

        public static void SaveToFile(this MemoryStream self,string fileName)
        {
            self.Seek(0, SeekOrigin.Begin);
            var bytes = new byte[self.Length];
            self.Read(bytes, 0, bytes.Length);
            File.WriteAllBytes(fileName, bytes);
        }
    }
}
